<?php
namespace Controller;
use Kuyuan\WqCore\controller\Controller;
use Kuyuan\WqCore\util\File;
use Model\MediaModel;
use Model\SettingMediaModel;
use Tool\mp4\Mp4;

/**
 * 素材库
 * Class Media
 * @package Controller
 */
class Media extends Controller
{

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 获取素材库列表
     */
    public function getList($_uid = 0,$_type,Array $_limit = array())
    {
        $MediaModel = MediaModel::where("uniacid",$this->_uniacid)
                      ->order("id","desc")
                      ->field(array("id","type","status","thumb","source"))
                      ->cache(!KUYUAN_DEBUG);
        if($_type == "image"){
            $MediaModel->where("type","image");
        } else if($_type == "video"){
            $MediaModel->where("type","video");
        }
        if($_uid === 0) $_uid = $this->_uid;
        if($_uid > 0) $MediaModel->where("uid",$_uid);
        if(count($_limit) > 0) $MediaModel->limit($_limit[0],$_limit[1]);
        return $MediaModel->select();
    }

    /**
     * 上传图片或者视频到素材库
     * @param string $_type 上传的文件类型
     * @param Array $_file 上传的文件资源
     * @return array
     */
    public function upload($_type,$_file)
    {
        global $_W;
        set_time_limit(0);
        load()->func('file');
        $_W['setting']['upload']['audio']['extentions'] = array("mp4","mov","rm","rmvb","wmv","avi","mpg","mpeg");

        $_insert_data = array(
            "uniacid" => $this->_uniacid,
            "uid" => $this->_uid,
            "type" => $_type,
            "filename" => $_file["name"],
            "size" => $_file["size"],
            "time" => TIMESTAMP
        );

        if($_type == 'image'){
            $_upload_result = $this->uploadImage($_file);
        } else {
            $_upload_result = $this->uploadVideo($_file);
        }

        if($_upload_result["code"] != 0){
            return $_upload_result;
        }

        $_data = $_upload_result["data"];
        $_remote = $_upload_result["remote"];
        $_insert_data = array_merge($_insert_data,$_data);
        if($_media_id = MediaModel::createId($_insert_data)){
            $_return = array(
                "id"=>$_media_id,
                "type"=>$_type,
                "status"=>$_insert_data["status"],
                "thumb"=> tomedia($_insert_data["thumb"]),
                "source"=> $_data["source"]
            );
            if($_type == "video"){
                $_return["video_url"] = tomedia($_data["source"]);
            }
            $_result = array("code"=>0,"data"=>$_return,"remote"=>$_remote);
        } else {
            $_result = array("code"=>602,"msg"=>"上传失败，未知错误");
        }
        return $_result;
    }

    /**
     * 上传图片
     * @param array $_file 上传图片的资源
     * @return array
     */
    private function uploadImage($_file)
    {
        $_data = array(
            "code"=>0,
            // 需要上传远程附件
            "remote" => array(),
            // 数据
            "data" => array(
                "status"=>SettingMediaModel::where("uniacid",$this->_uniacid)
                        ->cache(!KUYUAN_DEBUG)
                        ->value("is_check") ? 3 : 1
            )
        );
        $_result = file_upload($_file);

        if(!isset($_result["success"]) || !$_result["success"]){
            return array("code"=>600,"msg"=>$_result["message"]);
        }

        $_data["data"]["source"] = $_result["path"];
        $_data["data"]["thumb"] = file_image_thumb(ATTACHMENT_ROOT.'/'.$_result['path'],'',300);
        if($this->_w['setting']['remote']['type'] != 0){
            $_data["remote"][] = $_data["data"]["source"];
            $_data["remote"][] = $_data["data"]["thumb"];
        }
        return $_data;
    }

    /**
     * 上传视频
     * @param array $_file
     * @return array
     */
    private function uploadVideo($_file){
        $SettingMedia = SettingMediaModel::where("uniacid",$this->_uniacid)->cache(!KUYUAN_DEBUG);
        $_data = array(
            "code"=>0,
            // 需要上传远程附件
            "remote" => array(),
            // 数据
            "data" => array("status"=>
                $SettingMedia->value("is_check") ? 3 : 1
            )
        );
        $_result = file_upload($_file,"video");
        if(!isset($_result["success"]) || !$_result["success"]){
            return array("code"=>600,"msg"=>$_result["message"]);
        }
        $Mp4 = new Mp4(ATTACHMENT_ROOT.'/'.$_result["path"]);
        $_max_duration = SettingMediaModel::where("uniacid",$this->_uniacid)->value("duration");
        if(round($Mp4->_duration) > $_max_duration){
            return array("code"=>600,"msg"=>"上传视频长度不能大于".$_max_duration."秒");
        }
        $_thumb = File::path("images",'jpg');
        $_data["data"]["thumb"] = $Mp4->thumb($_thumb);
        $_data["data"]["source"] = $_result["path"];
        $_remote = array($_data["data"]["thumb"]);
        if(!$SettingMedia->value("transcoding")){
            $_remote[] = $_result["path"];
        } else {
            $_data["data"]["status"] = 2;
        }
        if($this->_w['setting']['remote']['type'] != 0){
            $_data["remote"] = $_remote;
        } else {
            unset($_remote);
        }
        return $_data;
    }

    /**
     * 上传远程图片附件
     * @param array source 要上传的资源
     */
    public function remote(Array $_source)
    {
        ignore_user_abort(true);
        set_time_limit(0);
        load()->func('file');
        sleep(10);
        foreach($_source as $_v){
            file_remote_upload($_v);
        }
    }

    /**
     * 视频转码
     * @param int $_media_id 素材库id
     * @param string $_source 素材本地服务器相对路径
     */
    public function transcoding($_media_id,$_source)
    {
        ignore_user_abort(true);
        set_time_limit(0);
        load()->func('file');
        $_file = ATTACHMENT_ROOT."/".$_source;
        $Mp4 = new Mp4($_file);
        $_path = File::path("videos","mp4");
        try {
            $_path = $Mp4->save($_path);
        } catch (\Exception $e){
            // 转码失败
            MediaModel::where("id",$_media_id)
                        ->update(array("status"=>4));
            exit;
        }
        $_size = filesize(ATTACHMENT_ROOT."/".$_path);
        unlink($_file);
        if($this->_w['setting']['remote']['type'] != 0){
            file_remote_upload($_path);
        }
        MediaModel::where("id",$_media_id)
                   ->update(
                       array(
                           "source"=>$_path,
                           "size" => $_size,
                           "status" => SettingMediaModel::where("uniacid",$this->_uniacid)
                                                          ->cache(!KUYUAN_DEBUG)
                                                          ->value("is_check") ? 3 : 1
                       )
                   );
    }

    /**
     * 删除素材
     */
    public function delete($_media_id)
    {
        $_media = MediaModel::where("id",$_media_id)
            ->field(array("thumb","source"))
            ->noGetAttr(false)
            ->find();
        if($_result = MediaModel::delete($_media_id,true)){
            load()->func('file');
            file_delete($_media['source']);
            file_delete($_media['thumb']);
            file_remote_delete($_media['source']);
            file_remote_delete($_media['thumb']);
        }
        return $_result;
    }

    /**
     * 编辑素材
     * @param $_media_id
     * @param array $_data
     * @return mixed
     */
    public function edit($_media_id, Array $_data)
    {
        return MediaModel::where("id",$_media_id)->update($_data);
    }

    /**
     * 通过素材库id集合返回封面
     */
    public function idsToThumb($_media_ids)
    {
        $_data = array();
        foreach($_media_ids as $_media_id) {
            $_data[] = tomedia(MediaModel::where("id",$_media_id)->value("thumb"));
        }
        return $_data;
    }

    /**
     * 获取指定用户素材库内存
     * @param int $_uid
     * @return array
     */
    public function getUserMemory($_uid = 0)
    {
        if(!$_uid) $_uid = $this->_uid;
        $_default_size = SettingMediaModel::where("uniacid",$this->_uniacid)
                            ->value("default_size");
        $_default_size = $_default_size * 1024 * 1024;
        $_sized = (int) MediaModel::where("uid",$_uid)->sum("size");
        return array("size"=>$_default_size,"sized"=>$_sized);
    }

    /**
     * manage端获取需要审核的素材列表
     * @param array $_limit
     * @return mixed
     */
    public function getCheckList(Array $_limit)
    {
        return MediaModel::where("uniacid",$this->_uniacid)
            ->where("status",3)
            ->field(array("id","type","uid","type","source","thumb"))
            ->order("id","desc")
            ->limit($_limit[0],$_limit[1])
            ->select();
    }

    /**
     * manage端获取需要审核的素材列表总数
     */
    public function getCheckTotal()
    {
        return MediaModel::where("uniacid",$this->_uniacid)
            ->where("status",3)
            ->count();
    }

    /**
     * 获取素材库指定素材
     * @param $_media_id
     * @param $_field
     * @return mixed
     */
    public function value($_media_id,$_field)
    {
        return MediaModel::where("id",$_media_id)->value($_field);
    }
}